import axios from 'axios'
import { Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
})


// request interceptor
service.interceptors.request.use(
  config => {

    // config.baseURL = httpEnvironment[config.link]
    // do something before request is sent
    console.log('-------------------------------')
    console.group('发送http请求')
    console.log(`baseURL: ${config.baseURL}`)
    console.log(`url: ${config.url}`)
    console.groupEnd()
    // loading show
    // store.commit('loading/SET_LOAD', true);
    // token empty
    config.headers['X-Token'] = getToken() || '123456'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.group(`http请求成功回调`)
    console.log('请求返回值：', response.data)
    console.groupEnd()
    console.log('-------------------------------')

    if (response.data.code === 401) {
      Notification({
        title: '错误',
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    }
    if (response.data.code === 500) {
      Notification({
        title: '错误',
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response || 'Error'))
    }

    return response.data
  },
  error => {
    // for debug
    console.group('http请求失败回调')
    console.log(error.response)
    console.groupEnd()
    console.log('-------------------------------')

    return Promise.reject(error)
  }
)

export default service
